package com.example.rpc.framework.protocl.http;

import com.example.rpc.test.IndexServlet;
import org.apache.catalina.Context;
import org.apache.catalina.Engine;
import org.apache.catalina.Host;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Server;
import org.apache.catalina.Service;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardEngine;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.startup.Tomcat;

public class HttpServer {
    //以下模拟tomcat中的server.xml配置
    public void start(String hostname,Integer port){
        try {
            start1(port);
        } catch (LifecycleException e) {
            e.printStackTrace();
        }
    }

    //这个方法行不通
    public  void start2(String hostname,Integer port){
        Tomcat tomcat=new Tomcat();

        Server server=tomcat.getServer();
        Service service=server.findService("Tomcat");

        Connector connector=new Connector();
        connector.setPort(port);

        Engine engine=new StandardEngine();
        engine.setDefaultHost(hostname);

        Host host=new StandardHost();
        host.setName(hostname);

        String contextPath="";
        Context context=new StandardContext();
        context.setPath(contextPath);
        connector.addLifecycleListener(new Tomcat.FixContextListener());

        host.addChild(context);
        engine.addChild(host);

        service.setContainer(engine);
        service.addConnector(connector);

        tomcat.addServlet(contextPath,"dispatcher",new DispatcherServlet());
        context.addServletMappingDecoded("/*","dispatcher");//接受所有的请求
        try{
            tomcat.start();
            tomcat.getServer().await();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public  void start1(int port) throws LifecycleException {
        String CONTEXT_PATH = "";

        Tomcat tomcat = new Tomcat();
        tomcat.setPort(port);
        tomcat.getHost().setAutoDeploy(false);
        //创建上下文
        StandardContext context = new StandardContext();
        context.setPath(CONTEXT_PATH);
        context.addLifecycleListener(new Tomcat.FixContextListener());
        tomcat.getHost().addChild(context);

        //创建Servlet
        tomcat.addServlet(CONTEXT_PATH,"dispatcher",new DispatcherServlet());
        //servlet映射
        context.addServletMappingDecoded("/*","dispatcher");
        tomcat.start();
        //异步接受请求
        System.out.println("start success!");
        tomcat.getServer().await();
    }
}
